package stl

// plugin_manager.go
import (
	"fmt"
	"path/filepath"
	"plugin"

	x "gitee.com/shexk/plugin"
)

const RunMode bool = false

type PluginManager struct {
	Plugins map[string]x.Plugin
	AppObj  *x.AppObj
}

func NewPluginManager(appobj *x.AppObj) *PluginManager {
	return &PluginManager{
		Plugins: make(map[string]x.Plugin),
		AppObj:  appobj,
	}
}

// LoadPlugin 加载指定路径的插件
func (pm *PluginManager) loadPlugin(path string) error {
	p, err := plugin.Open(path)
	if err != nil {
		return err
	}

	sym, err := p.Lookup("LoadPlugin")
	if err != nil {
		return err
	}

	factory, ok := sym.(func() x.Plugin)
	if !ok {
		return fmt.Errorf("invalid plugin factory")
	}

	plugin := factory()

	pm.Plugins[plugin.Meta().Name] = plugin
	return nil
}

func (pm *PluginManager) LoadAllPlugin() {
	// 加载所有插件
	appSupportDir, err := GetResourcesDir(RunMode)
	if err != nil {
		return
	}
	PluginsPath := filepath.Join(appSupportDir, "plugins/*.so")
	GetLog().WriteLog(Log_Debug, "Load Plugins,Path="+PluginsPath)
	plugins, _ := filepath.Glob(PluginsPath)
	for _, p := range plugins {
		if err := pm.loadPlugin(p); err != nil {
			//fmt.Println("Open Plugin Error,File:", p, "Error:", err)
			GetLog().WriteLog(Log_Debug, "Open Plugin Error,File:", p, "Error:", err)
		} else {
			GetLog().WriteLog(Log_Debug, "Load Plugin Success,File="+p)
		}
	}

	//执行初始化逻辑
	for _, p := range pm.Plugins {
		if err := p.Init(pm.AppObj); err != nil {
			fmt.Println("Init Error:", err)
		}
	}
	// 执行插件逻辑
	for _, p := range pm.Plugins {
		if err := p.Start(); err != nil {
			fmt.Println("Execute Error:", err)
		}
	}
}

// UnloadPlugin 卸载插件（需结合具体场景实现）
func (pm *PluginManager) UnloadPlugin(name string) {
	if p, ok := pm.Plugins[name]; ok {
		p.Stop()
		delete(pm.Plugins, name)
	}
}

// func (pm *PluginManager) getConfig(meta PluginMeta) map[string]interface{} {
// 	viper.SetConfigName(meta.Name)
// 	viper.AddConfigPath("configs/")
// 	if err := viper.ReadInConfig(); err != nil {
// 		return nil
// 	}
// 	return viper.AllSettings()
// }

// hot_reload.go
// func (pm *PluginManager) WatchPlugins() {
// 	watcher, _ := fsnotify.NewWatcher()
// 	defer watcher.Close()

// 	go func() {
// 		for {
// 			select {
// 			case event := <-watcher.Events:
// 				if event.Op&fsnotify.Write == fsnotify.Write {
// 					//pm.UnloadPlugin(event.Name)
// 					//pm.LoadPlugin(event.Name)
// 				}
// 			}
// 		}
// 	}()
// }
